<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Feedback extends MY_Controller{

	public function __construct()
	{
		parent::__construct();
		$this->load->model('t_feedback');
	}

	public function user_rating(){
		$post = parent::validation_user();

		$userId = $post[T_USERS][USER_ID];

		if(!isset($post[PRODUCT_ID])){
			parent::print_result('Missing key or value ' . PRODUCT_ID);exit();
		}else{
			$productId = $post[PRODUCT_ID];
		}

		if(!isset($post[FBACK_RATE])){
			parent::print_result('Missing key or value '. FBACK_RATE);exit();
		}else{
			$rateValue = $post[FBACK_RATE];
		}

		if(isset($post[FBACK_CONTENT])){
			$content = $post[FBACK_CONTENT];
		}else{
			$content = '';
		}

		$query = $this->t_feedback->get_data_by_property(array(FBACK_USER_ID => $userId, FBACK_PRO_ID => $productId));

		if(!empty($query)){
			$this->t_feedback->update_data_by_property(array(FBACK_CONTENT => $content, FBACK_RATE => $rateValue), array(FBACK_USER_ID => $userId, FBACK_PRO_ID => $productId));

			$query = $this->t_feedback->get_data_by_property(array(FBACK_USER_ID => $userId, FBACK_PRO_ID => $productId));
		}else{
			$query = $this->t_feedback->set_data(array(FBACK_CONTENT=> $content, FBACK_USER_ID => $userId, FBACK_PRO_ID => $productId, FBACK_RATE => $rateValue), 1);
		}

		// update rate of user
		$rateValue = $this->t_feedback->calculatorRateValue($productId);
		if(!empty($rateValue)){
			$this->load->model('t_product');
			$user = $this->t_product->get_data_by_id($productId);
			if(!empty($user)){

				// var_dump($rateValue);exit();
				$this->load->model('t_user');
				$this->t_user->update_data_by_id(array(USER_RATE => $rateValue[0]['rating']), $user[0][PRODUCT_USER_ID]);
			}	
		}
		parent::print_result($query[0], SUCCESS_VALUE);exit();
	}
}